package ro.ubbcluj.android.PhysiTrack;

import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileWriter;
import java.util.Random;

import process.ImageErrorException;
import process.ProcIm;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.ImageFormat;
import android.graphics.Rect;
import android.graphics.YuvImage;
import android.hardware.Camera;
import android.hardware.Camera.PreviewCallback;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

public class PhysiTrackActivity extends Activity {

	private Context context = this;
	private static final String TAG = PhysiTrackActivity.class.getSimpleName();
	private SurfaceView preview=null;
	private SurfaceHolder previewHolder=null;
	private Camera camera=null;
	private boolean inPreview=false;
	private EditText text1, text2;
	private EditText text3, text4, text5;
	private Calculate calculate;
	private TextView velText,accText;
	private double acceleration, velocity;
	private double fps, szigmaM, szigmaW;
	private File currentDir;
	private double[][] matrix;
	private int db;
	Bitmap bitmapPicture;
	private String newFolder;
	private Random r;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		r = new Random();
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN );
		setContentView(R.layout.main);
		newFolder = "/PhysiTrack";
		String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
		File myNewFolder = new File(extStorageDirectory + newFolder);
		myNewFolder.mkdir();
		fps = 0;
		preview=(SurfaceView)findViewById(R.id.cameraView);
		previewHolder=preview.getHolder();
		previewHolder.addCallback(surfaceCallback);
		previewHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);

		text1 = (EditText)findViewById(R.id.accelerationField);
		text2 = (EditText)findViewById(R.id.velocityField);
		text1.setFocusable(false);
		text2.setFocusable(false);

		text3 = (EditText)findViewById(R.id.fpsField);
		text4 = (EditText)findViewById(R.id.szimgaMField);
		text5 = (EditText)findViewById(R.id.szimgaWField);


		velText=(TextView)findViewById(R.id.velocityText);
		accText=(TextView)findViewById(R.id.accelerationText);
		velText.setVisibility(View.INVISIBLE);
		accText.setVisibility(View.INVISIBLE);

		UIHandler handler = new UIHandler(text1, text2);
		calculate = new Calculate(this, handler);

		Button startCalc = (Button)findViewById(R.id.startButton);
		startCalc.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				try{
					if(fps == 0){
						String text=text3.getText().toString();   
						fps=Double.parseDouble(text);
						text=text4.getText().toString();
						szigmaM=Double.parseDouble(text);
						text=text5.getText().toString();
						szigmaW=Double.parseDouble(text);
						//PhysiObject p = new PhysiObject();
						text3.setVisibility(View.INVISIBLE);
						text4.setVisibility(View.INVISIBLE);
						text5.setVisibility(View.INVISIBLE);

						LinearLayout rlayout1 = (LinearLayout) findViewById(R.id.info);
						rlayout1.setVisibility(1);
						velText.setText("velocity");
						accText.setText("acceleration");
						velText.setVisibility(View.VISIBLE);
						accText.setVisibility(View.VISIBLE);
						Button diag = (Button)findViewById(R.id.diagramButton);
						diag.setClickable(false);
						Button startCalc = (Button)findViewById(R.id.startButton);
						startCalc.setClickable(false);
						//calculate.startCalculate();
					}
					ProcIm.init();
					camera.setPreviewCallback(new PreviewCallback() {

						public void onPreviewFrame(byte[] data, Camera camera) {

							try {					

								Camera.Parameters parameters = camera.getParameters();

								int width = parameters.getPreviewSize().width;
								int height = parameters.getPreviewSize().height;

								ByteArrayOutputStream outstr = new ByteArrayOutputStream();
								Rect rect = new Rect(0, 0, width, height); 
								YuvImage yuvimage=new YuvImage(data,ImageFormat.NV21,width,height,null);
								yuvimage.compressToJpeg(rect, 50, outstr);
								byte[] imageBytes = outstr.toByteArray();
								Bitmap image = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.length);
								calculate.setImage(image);
								bitmapPicture = calculate.getImage();				
								//------------------------------------------------------------------------------				
								int[] pos = new int[2];
								
								try{					
									pos=ProcIm.getPos(bitmapPicture);
									calculate.setData(pos[0],pos[1]);
									//System.out.println(pos[0] + " "+ pos[1]);
									//pos[0]=100;
									//pos[1]=100;

								}catch(ImageErrorException e){
									AlertDialog alertDialog = new AlertDialog.Builder(PhysiTrackActivity.this).create();
									alertDialog.setMessage(e.getMessage());
									alertDialog.show();
									camera.setPreviewCallback(null);
									findViewById(R.id.stopButton).performClick();
									//System.out.println(pos[0] + " "+ pos[1]);
								}
								//p.addData(pos[0],pos[1],0.5);
								//---------------------------------------------
								Log.d(TAG, image.getWidth() + " " + image.getHeight());


							} catch (Exception e) {
								Log.d(TAG, e.getMessage());	
							}
						}

					});

				}
				catch (NumberFormatException e){
					AlertDialog alertDialog = new AlertDialog.Builder(PhysiTrackActivity.this).create();
					alertDialog.setMessage("Type the parameters!");
					alertDialog.show();
				}
			}
		});
		Button stopCalc = (Button)findViewById(R.id.stopButton);
		stopCalc.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				calculate.stopCalculate();
				camera.setPreviewCallback(null);
				Button diag = (Button)findViewById(R.id.diagramButton);
				diag.setClickable(true);
				Button startCalc = (Button)findViewById(R.id.startButton);
				startCalc.setClickable(true);
			}
		});


		Button diagram = (Button)findViewById(R.id.diagramButton);
		diagram.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				AlertDialog.Builder builder = new AlertDialog.Builder(PhysiTrackActivity.this);
				builder.setMessage("Save the current datas?")
				.setCancelable(false)
				.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						dialog.cancel();
						final Dialog savedialog = new Dialog(context);
						savedialog.setContentView(R.layout.savefile);
						savedialog.setTitle("Result");

						final EditText filename = (EditText)savedialog.findViewById(R.id.filename);

						Button save = (Button) savedialog.findViewById(R.id.saveButton);
						save.setOnClickListener(new OnClickListener() {
							public void onClick(View v) {
								String name = filename.getText().toString();
								String path = "mnt/sdcard/"+newFolder+"/" + name + ".txt";
								currentDir = new File(path);
								resultToFile(currentDir);
								Intent intent = new Intent(PhysiTrackActivity.this,DiagramActivity.class);
								intent.putExtra("filepath", path);
								savedialog.dismiss();
								startActivity(intent);
							}
						});

						Button cancel = (Button) savedialog.findViewById(R.id.cancelButton);
						cancel.setOnClickListener(new OnClickListener() {
							public void onClick(View v) {
								savedialog.dismiss();
								Intent intent = new Intent(PhysiTrackActivity.this,FileChooser.class);
								startActivity(intent);

							}
						});

						savedialog.show();
					}
				})
				.setNegativeButton("No", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						dialog.cancel();
						Intent intent = new Intent(PhysiTrackActivity.this,FileChooser.class);
						startActivity(intent);

					}
				});
				AlertDialog alert = builder.create();
				alert.show();


			}
		});

		//camera kep rogzitese
		//camera.takePicture(myShutterCallback, myPictureCallback_RAW, myPictureCallback_JPG);
	}

	@Override
	public void onStart(){
		Log.d(TAG, "start application");

		super.onStart();
	}

	@Override
	public void onStop(){
		Log.d(TAG, "stop application");

		super.onStop();
	}

	public void resultToFile(File file) {

		try{

			//File file = Environment.getExternalStorageDirectory();
			FileWriter fw = new FileWriter(file);
			BufferedWriter out = new BufferedWriter(fw);
			//Tomb tomb=new Tomb(matrix);
			db=calculate.getDb();
			matrix=new double[db][5];
			matrix=calculate.getData();

			//double[][] result = tomb.getResult();
			for (int i=0;i<db;i++){
				for(int j=0;j<5;j++){
					out.write(matrix[i][j]+" ");
				}
				out.write("\n");
			}

			out.close();
			Log.d(TAG, "stop write to file");
		}
		catch (Exception e) {
			e.printStackTrace();
		}
	}
	private Camera.Size getBestPreviewSize(int width, int height, Camera.Parameters parameters){
		Camera.Size result=null;
		for (Camera.Size size : parameters.getSupportedPreviewSizes()){
			if (size.width<=width && size.height<=height){
				if (result==null) {
					result=size;
				}
				else {
					int resultArea=result.width*result.height;
					int newArea=size.width*size.height;
					if (newArea>resultArea){
						result=size;
					}
				}
				Log.d(TAG,"" + size.width + "  " + size.height);
			}
		}
		return(result);
	}

	SurfaceHolder.Callback surfaceCallback=new SurfaceHolder.Callback(){
		public void surfaceCreated(SurfaceHolder holder){
			try {
				camera=Camera.open();
				camera.setPreviewDisplay(previewHolder);

			}
			catch (Throwable t) {
				Log.d(TAG,"Exception in setPreviewDisplay()", t);
			}
		}
		public void surfaceChanged(SurfaceHolder holder, int format, int width, int height){

			Camera.Parameters parameters=camera.getParameters();
			Camera.Size size=getBestPreviewSize(width, height, parameters);
			if (size!=null){
				parameters.setPreviewSize(size.width, size.height);
				camera.setDisplayOrientation(90);
				camera.setParameters(parameters);
				camera.startPreview();
				inPreview=true;
			}


		}
		public void surfaceDestroyed(SurfaceHolder holder){
			if (inPreview){
				camera.setPreviewCallback(null);
				camera.stopPreview();
			}
			camera.release();
			camera=null;
			inPreview=false;
		}



		protected void MostrarFoto(String string) {
			// TODO Auto-generated method stub

		}
	};
}